<?php

class Club extends MY_SecuredController {

	public function __construct() {
		parent::MY_SecuredController();

		$this->requireRole('User');
		
		$this->load->helper(array('form','url'));
		$this->load->library('form_validation');
		
		$this->lang->load('home');
		$this->lang->load('profile/club');
	}
	
	public function index($civlid) {
        $this->_preRender($civlid);
        
		$person = PersonModel::getPerson($civlid);
		
        if (!$this->_checkAdminClub($person)) {
            return false;
        }
        
		$data['person'] = $person;
		$data['pilot'] = $person->Pilot;
		
		$this->render('profile/club/index', $data);
	}

	public function add($civlid) {
        $this->requireRole('Owner');
		$this->_preRender($civlid);
        
		if (!$this->input->post('action')) {
			$person = PersonModel::getPerson($civlid);
			
			$data['clubs'] = array();
			$this->_addClubPilots($civlid, $data);
			
			$data['person'] = $person;
			$data['pilot'] = $person->Pilot;
			
			$this->render('profile/club/add', $data);
		}
		else {
			$club = Doctrine::getTable('ClubModel')->find($this->input->post('club'));
			$data['clubs'] = array();
			$this->_addClubPilots($civlid, $data);
								
			if ($club) {
				log_message('debug', '>>> joined = '.$this->input->post('joined'));

				$person = PersonModel::getPerson($civlid);
				$pilot = $person->Pilot;

				$index = count($pilot->Clubs) == 0? 0 : count($pilot->Clubs);

				$pilot->Clubs[$index] = $club;
				try {
					$pilot->save();
				}
				catch (Exception $e) {
					$data['person'] = $person;
					$data['pilot'] = $pilot;
					
					$this->render('profile/club/add', $data, $this->error(array(
						'message' => 'Ooops, the club could not be added - please try again later.',
						'exception' => $e
					)));
					return;
				}

				foreach ($pilot->ClubPilotModel as $pc):
					if ($pc->club_id == $club->id):
						$pc->joined =  $this->input->post('joined');
						$pc->member = $this->input->post('member');
						
						try {
							$pc->save();
						}
						catch (Exception $e) {
		                    $data['person'] = $person;
		                    $data['pilot'] = $pilot;
							
                            $this->render('profile/club/index', $data, $this->error(array(
								'message' => 'Ooops, the club could not be added - please try again later.',
							'	exception' => $e
							)));
							return;
						}

						break;
						
					endif;
				endforeach;

				$this->redirect('profile/club/index/'.$person->id, 'Club has been successfully added!');
			}
		}
	}
    
	public function edit($civlid, $clubid) {
		$this->requireRole('Admin');
        $this->_preRender($civlid);

        $person = PersonModel::getPerson($civlid);
        
        // check permissions: owners can edit everything, admins only if the person belongs to their club
        if (!$this->_checkAdminClub($person)) {
            return false;
        }
        
        $pilot = $person->Pilot;

        if (!$this->input->post('action')) {
            $data['person'] = $person;
            $data['pilot'] = $person->Pilot;

            foreach ($pilot->Clubs as $g) {
                if ($g->id == $clubid) {
                    $data['club'] = $g;
                    $data['pilot_club'] = $g->ClubPilotModel[0];

                    $this->render('profile/club/edit', $data);
                    break;
                }
            }
        }
        else {
            echo "editing record $clubid<br/>";

            foreach ($pilot->ClubPilotModel as $pc) {
                if ($pc->club_id == $clubid) {
                    $pc->joined =  $this->input->post('joined');
                    $pc->member = $this->input->post('member');

                    try {
                        $pc->save();
                    }
                    catch (Exception $e) {
                        $this->render('profile/club/index', $data, $this->error(array(
                            'message' => 'Ooops, the club could not be added - please try again later.',
                            'exception' => $e
                        )));
                        return;
                    }
                    $this->redirect('profile/club/index/'.$person->id, 'Club has been successfully updated!');
                    break;

                }
            }

            $this->redirect('profile/club/index/'.$person->id, 'Club not found?');
        }
    }
	
	public function delete($civlid, $clubid = null) {
		$this->requireRole('Owner');
		$this->_preRender($civlid);

        $person = PersonModel::getPerson($civlid);
        $clubs = $person->Pilot->ClubPilotModel;
		        
        $data['person'] = $person;
        $data['pilot'] = $person->Pilot;
		
		if ($this->input->post('action')) {
			
			$data['pilot'] = $person->Pilot;

			foreach ($clubs as $c):
				if ($this->input->post('cid_'.$c->club_id) != ""):
					try {
						$c->delete();
					}
					catch (Exception $e) {
						$this->render('profile/club/index', $data, $this->error(array(
							'message' => 'Ooops, one or more clubs could not be deleted.',
							'exception' => $e
						)));
						return;
					}
				endif;
			endforeach;
			
			$this->redirect('profile/club/index/'.$person->id, 'Club has been successfully deleted!');
		}
        else if ($clubid != null) {
            foreach ($clubs as $g) {
                if ($g->club_id == $clubid) {
                    try {
                        $g->delete();
                        $this->redirect('profile/club/index/'.$person->id, 'Club has been successfully deleted!');
                    }
                    catch (Exception $e) {
                        $this->render('profile/club/index', $data, $this->error(array(
                            'message' => 'Ooops, one or more clubs could not be deleted.',
                            'exception' => $e
                        )));
                        return;
                    }
                }
            }
                
            $this->render('profile/club/index', $data, $this->error(array(
                'message' => "Club '$clubid' could not be found!"
            )));
        }
	}
	
	private function _addClubPilots($civlid, &$data) {
		$person = PersonModel::getPerson($civlid);
		
		$clubs = Doctrine::getTable('ClubModel')->findAll();
		$data['clubs'] = array();
			
		$clubPilots = array();
		foreach ($person->Pilot->Clubs as $pc):
			$clubPilots[] = $pc->id;
		endforeach;

		foreach ($clubs as $c):
			if (!in_array($c->id, $clubPilots, true)):
				$data['clubs'][$c->id] = $c->name;
			endif;
		endforeach;
	}
}
?>
